package com.sayice.gomoku.filter;

import com.sayice.gomoku.utils.JdbcUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 事务管理
 */
public class TransactionFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        try {
            filterChain.doFilter(servletRequest, servletResponse);
            // 提交事务
            JdbcUtils.commitAndClose();
        } catch (Exception e) {
            // 回滚事务
            JdbcUtils.rollbackAndClose();
            e.printStackTrace();
            // 将异常抛给 Tomcat 管理
            throw new RuntimeException(e);
        }
    }
}
